package com.my.aslife.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.my.aslife.controller.FileController;
import com.my.aslife.module.common.*;
import com.my.aslife.module.entity.RunnerDetail;
import com.my.aslife.mapper.RunnerDetailMapper;
import com.my.aslife.module.entity.User;
import com.my.aslife.module.entity.dtos.RunnerDetailAllowDto;
import com.my.aslife.module.entity.dtos.RunnerDetailQueryDto;
import com.my.aslife.module.entity.dtos.UserDto;
import com.my.aslife.service.IRunnerDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.aslife.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2022-12-12
 */
@Service
public class RunnerDetailServiceImpl extends ServiceImpl<RunnerDetailMapper, RunnerDetail> implements IRunnerDetailService {

    @Autowired
    private FileController fileController;

    @Autowired
    private RunnerDetailMapper runnerDetailMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;


    @Override
    public ResponseResult uploadApplyRunnerImg(MultipartFile file) {
        ResponseResult responseResult = fileController.uploadFile(file, UploadTypeThreadLocal.getUploadType());
        if (!responseResult.getCode().equals("200")) {
            return responseResult;
        }

        String url = (String) responseResult.getData();
        Integer uid = UserIdThreadLocal.get();
        String type = UploadTypeThreadLocal.getUploadType();
        RunnerDetail runnerDetailData = new RunnerDetail();
        runnerDetailData.setUid(Long.valueOf(uid));

        if (type.equals(UploadEnum.SFZ_FACE.getTypeCode())) {
            runnerDetailData.setSfzFaceUrl(url);

        } else if (type.equals(UploadEnum.SFZ_REVERSE.getTypeCode())) {
            runnerDetailData.setSfzReverseUrl(url);

        } else if (type.equals(UploadEnum.SOURCE.getTypeCode())) {
            runnerDetailData.setSourceUrl(url);
        }
        // 判断用户是否存在
        RunnerDetail runnerDetail = runnerDetailMapper.queryRunnerDetailByUID(uid);
        if (runnerDetail == null) {
            runnerDetailData.setCreateTime(new Date());
            save(runnerDetailData);
        } else {
            // 更新数据
            runnerDetailData.setUpdateTime(new Date());
            runnerDetailMapper.updateRunnerDetail(runnerDetailData);
        }

        return ResponseResult.ok(url);
    }

    @Override
    public ResponseResult queryRunnerDetailByUID(Long uid) {
        LambdaQueryWrapper<RunnerDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RunnerDetail::getUid, uid);
        RunnerDetail runnerDetail = getOne(lqw);

        return ResponseResult.ok(runnerDetail);
    }

    @Override
    public ResponseResult commitApply(Long uid) {
        // 已经提交了审核
        String key = RedisConstant.USER_APPLY_RUNNER + uid;
        String flag = stringRedisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(flag)) {
            return ResponseResult.failed(ErrorCode.FAST_APPLY_RUNNER);
        }
        // 状态 0 无状态 1 提交 2 失败 3 通过
        runnerDetailMapper.commitApply(uid, 1);
        stringRedisTemplate.opsForValue().set(RedisConstant.USER_APPLY_RUNNER + uid, " ");

        return ResponseResult.ok();
    }

    @Override
    public ResponseResult allowIntoRunner(RunnerDetailAllowDto runnerDetailAllowDto) {

        LambdaQueryWrapper<RunnerDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RunnerDetail::getUid, runnerDetailAllowDto.getUid());
        RunnerDetail runnerDetail = getOne(lqw);
        runnerDetail.setSourceHandle(runnerDetailAllowDto.getSourceData());
        runnerDetail.setPassTime(new Date());
        runnerDetail.setAdminUid(UserIdThreadLocal.get());
        runnerDetail.setStatus(3);

        return ResponseResult.ok();
    }

    @Override
    public ResponseResult getUserIllegalByPage(PageRequestVo pageRequestVo) {

        int c = pageRequestVo.getCurrent();
        int size = pageRequestVo.getPageSize();
        int start = (c - 1) * size;

        List<RunnerDetail> runnerDetailList = runnerDetailMapper.getUserIllegalByPage(start, size);

        List<Long> ids = new ArrayList<>();
        for (RunnerDetail runnerDetail : runnerDetailList) {
            ids.add(runnerDetail.getUid());
        }
        ResponseResult<List<User>> userListByUIDs = userService.getUserListByUIDs(ids);
        List<User> users = userListByUIDs.getData();

        List<RunnerDetailQueryDto> data = new ArrayList<>();
        RunnerDetailQueryDto runnerDetailQueryDto;
        for (int i = 0; i < users.size(); ++i) {
            User user = users.get(i);
            runnerDetailQueryDto = new RunnerDetailQueryDto();
            BeanUtils.copyProperties(user, runnerDetailQueryDto);
            for (RunnerDetail runnerDetail : runnerDetailList) {
                if (user.getUid() == runnerDetail.getUid().intValue()) {
                    BeanUtils.copyProperties(runnerDetail, runnerDetailQueryDto);
                    break;
                }
            }
            data.add(runnerDetailQueryDto);
        }

        return ResponseResult.ok(data, count());
    }

    @Override
    public ResponseResult queryRunnerDetailInfoByUID(Long uid) {
        LambdaQueryWrapper<RunnerDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RunnerDetail::getUid, uid);
        return ResponseResult.ok( getOne(lqw));
    }

    @Override
    public ResponseResult applyRunnerFail(RunnerDetail runnerDetail) {
        runnerDetail.setStatus(2);
        runnerDetailMapper.applyRunnerFail(runnerDetail);

        // 设置账号权限 10普通用户 11跑腿者 20审批跑腿者 21审批需求 99超级管理员
        User user = (User)userService.queryUserInfoByUID(runnerDetail.getUid()).getData();
        Integer type = user.getType();

        if (type < 11) {
            user.setType(11);
            userService.save(user);
        }

        return ResponseResult.ok();
    }

    @Override
    public ResponseResult applyRunnerOK(RunnerDetail runnerDetail) {
        LambdaQueryWrapper<RunnerDetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(RunnerDetail::getUid, runnerDetail.getUid());
        RunnerDetail one = getOne(lqw);

        one.setStatus(3);
        one.setAdminUid(UserIdThreadLocal.get());
        one.setPassTime(new Date());
        one.setSourceHandle(runnerDetail.getSourceHandle());
        User user = new User();
        user.setUid(Integer.parseInt(runnerDetail.getUid()+""));
        userService.updateUserRunner(user);

        runnerDetailMapper.deleteRunenrDetailByUID(runnerDetail.getUid());
        save(one);
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult runOk(Long orderId) {

        return null;
    }
}
